import React from 'react';
import { message, showModal } from '../../functionalComponent';
import { iup } from '../../util';
import { ITableAttachmentApi, ITableAttachmentApiProps, ITableAttachmentProps } from './interface';
import {
  attachDelete,
  attachSave,
  createZip,
  editCategory,
  getAttachmentCountBatch as getAttachmentCountBatchService,
  getDownloadFileUrl,
  getPreviewUrl,
  getZipDownloadInfo,
  shareSave,
  tableAttachInit
} from './service';
import { attachListDataRes } from './type';
import { downloadFile, getFileType, openTab as openTabApi } from './util';
import { OriginTableAttachment, TableAttachment } from './views';

const isDev = process.env.NODE_ENV === 'development';
const titleMap = {
  View: '文件查看',
  Edit: '文件编辑',
  Preview: '文件预览'
};

const getShareValue = (sharedOne, sharedOneName) => {
  const shareValue: { label: string; value: any }[] = [];
  if (sharedOne && sharedOneName) {
    const sharedOneList = sharedOne.split(',');
    const sharedOneNameList = sharedOneName.split(',');
    if (sharedOneList.length === sharedOneNameList.length) {
      for (let i = 0; i < sharedOneList.length; i++) {
        shareValue.push({ label: sharedOneNameList[i], value: sharedOneList[i] });
      }
    }
  }
  return shareValue;
};

export const getTableAttachmentApi = async (
  params: ITableAttachmentApiProps,
  cancelId?: string
): Promise<ITableAttachmentApi> => {
  const {
    asrSessionGuid: propAsrSessionGuid = '',
    asrFill: propAsrFill,
    asrFillName: propAsrFillName,
    unitNo: propUnitNo,
    orgNo: propOrgNo,
    projectNo: propProjectNo,
    uCode: propUCode,
    asrTable: propAsrTable,
    asrCode: propAsrCode,
    asrAttachTable = '',
    busTypeCode: propBusTypeCode,
    busUrl,
    approved = 0,
    customOpenTab,
    onSave,
    bizCode, // for accept
    labelConfig
  } = params;
  const busTypeCode = propBusTypeCode || iup.getPageInstance()?.busType;
  const openTab =
    typeof customOpenTab === 'function'
      ? (title, path, params) => customOpenTab(title, iup.handleUrl(path, params))
      : openTabApi;
  const userInfo = iup.getUser();
  const asrFill = propAsrFill ?? userInfo.userNo;
  const asrFillName = propAsrFillName ?? userInfo.userName;
  const unitNo = propUnitNo ?? userInfo.tenantNo;
  const orgNo = propOrgNo ?? userInfo.orgNo;
  const projCode = propProjectNo ?? userInfo.projCode;
  const uCode = propUCode ?? userInfo.ucode;
  const getTableAttachInfo = async () =>
    await tableAttachInit(
      {
        orgNo,
        tag: propAsrTable,
        busiIds: propAsrSessionGuid,
        unitNo,
        projCode,
        bizCode: bizCode || propBusTypeCode
      },
      cancelId
    );
  const tableAttachInfo = (await getTableAttachInfo()) || ({} as attachListDataRes);
  const asrSessionGuid = tableAttachInfo?.cursorId; // 临时会话标识
  const asrTable = propAsrTable || asrSessionGuid;
  const asrCode = propAsrCode || asrSessionGuid;

  const attachmentRecordList =
    tableAttachInfo?.data?.map((item) => {
      return {
        ...item,
        asrSessionGuid
      };
    }) ?? [];

  return {
    asrSessionGuid,
    asrFill,
    asrFillName,
    asrTable,
    asrCode,
    asrAttachTable,
    busTypeCode,
    orgNo,
    busUrl,
    uCode,
    tableAttachInfo,
    attachmentRecordList,
    labelConfig,
    getTableAttachInfo,
    handleEditOrView: async (file, type) => {
      const { asrName, asrFid, asrFill } = file;
      const fileType = getFileType(asrName);
      const url = '/WM/Archive/KingGridObject/KingGridObjectEdit';
      const params: any = {
        dbToken: uCode,
        RecordID: asrSessionGuid,
        BillId: asrFid,
        DataFrom: 'attachment',
        AsrName: asrName,
        FileType: `.${fileType}`,
        OpType: type,
        BillBusinessType: busTypeCode
      };
      openTab(titleMap[type], url, params);
    },
    handleDelete: async (id) => {
      const res = await attachDelete({
        fileIds: id,
        cursorId: asrSessionGuid
      });
      if (res?.code === 0) {
        message.success('删除成功');
        return true;
      } else {
        const msg = res?.message || '删除失败';
        message.error(msg);
      }
      return false;
    },
    handleDownload: async (files) => {
      const filesArr = iup.isArray(files) ? files : [files];
      const fileIds = filesArr.map((file) => file.asrFid).join(',');
      const res = await getDownloadFileUrl({ fileId: fileIds });
      if (res?.code === 0) {
        const downloadName = filesArr.length === 1 ? filesArr[0].asrName : Date.now();
        downloadFile(downloadName, res?.data?.link, 'url');
      }
    },
    handleZipDownload: async () => {
      const res = await createZip({
        busiIds: propAsrSessionGuid,
        tag: asrTable,
        orgNo,
        projCode,
        unitNo
      });
      if (res?.code === 0) {
        const { data } = res;
        const getZipDownloadInfoLoop = async () => {
          const res = await getZipDownloadInfo({ id: data.id });
          if (res?.code === 0) {
            const { data } = res;
            if (data.pace < 100) {
              setTimeout(getZipDownloadInfoLoop, 2000);
            } else {
              downloadFile('package', data['downloadUrl'], 'url');
            }
          }
        };
        setTimeout(() => {
          getZipDownloadInfoLoop();
        }, 500);
      }
    },
    handlePreview: async (file) => {
      const res = await getPreviewUrl({ fileId: file.asrFid });
      if (res?.code === 0) {
        const url = res?.data?.link;
        // const origin = isDev ? 'http://10.18.3.205:8081' : location.origin;
        // const prevUrl = `${origin}/${url}`;
        openTab(titleMap.Preview, url);
      }
    },
    /**
     * @deprecated
     */
    handleEditCategory: async (checkedList) => {
      const res = await iup.external.openHelp({
        type: 'SingleHelp',
        helpId: 'AttachmentTypeHelpPlugin',
        valueField: 'typeid',
        labelField: 'typename',
        clientSqlFilter: `cuid=${(tableAttachInfo as any).cuid}&bustypecode=${busTypeCode}`
      });
      if (res) {
        const editRes = await editCategory(
          {
            asrSessionGuid,
            asrFids: checkedList.map((item) => item.asrFid).join(','),
            typeId: res.value
          },
          uCode
        );
        if (editRes?.code === 0) {
          message.success('操作成功');
        }
      }
    },
    handleChangeShareType: async (v, data) => {
      const { asrFid, sharedOne, sharedOneName } = data;
      if (v === 'self') {
        await shareSave(
          {
            asrSessionGuid,
            asrFid,
            sharedOne: asrFill,
            sharedOneName: asrFillName,
            shareType: v
          },
          uCode
        );
      } else {
        const helpTypeMap = {
          empno: 'UserHelp',
          dept: 'DeptHelp'
        };
        const helpType = helpTypeMap[v] || 'UserHelp';
        const res = await iup.external.openHelp({
          type: helpType,
          multiple: true,
          value: getShareValue(sharedOne, sharedOneName)
        });
        if (res) {
          await shareSave(
            {
              asrSessionGuid,
              asrFid,
              sharedOne: res.map((item) => item.value).join(','),
              sharedOneName: res.map((item) => item.label).join(','),
              shareType: v
            },
            uCode
          );
        }
      }
    },
    handleValid: () => {
      return true;
    },
    handleSave: async (params: any = {}) => {
      const res = await attachSave([
        {
          cursorId: asrSessionGuid,
          tag: asrTable,
          unitNo,
          orgNo,
          projCode
        }
      ]);
      if (res?.code === 0) {
        onSave?.(res?.data);
        message.success('保存成功');
      }
    }
  };
};

export const getAttachmentCountBatch = async (params) => {
  const { asrCode, asrTable } = params;
  const res = await getAttachmentCountBatchService({ asrCode, asrTable });
  return res;
};

const defaultAttachmentModalConfig = {
  title: '附件',
  width: 1000,
  height: 700,
  footer: false
};
export const openAttachment = (props: ITableAttachmentProps) =>
  new Promise((resolve) => {
    const { control = true, categoryStyle = {}, style = {}, ...restProps } = props;
    const apiRef = React.createRef<any>();
    const getResult = async (closeStatus) => {
      const api = apiRef.current?.getApi() ?? {};
      const result = await api.getResult();
      const isChanged = api?.isChanged?.();
      return {
        ...result,
        isChanged,
        closeStatus
      };
    };
    const handleOk = async (ins) => {
      const api = apiRef.current?.getApi() ?? {};
      if (api.uploadingRef.current) {
        iup.message('正在上传中，无法关闭弹窗');
        return;
      }
      if (api.handleValid?.()) {
        await (!control && api?.handleSave?.());
        const result = await getResult('ok');
        ins.destroy();
        resolve(result);
      }
    };
    const handleCancel = async (ins) => {
      const result = await getResult('cancel');
      ins.destroy();
      resolve(result);
    };
    showModal({
      ...defaultAttachmentModalConfig,
      params: { isModal: true, handleOk, handleCancel },
      content: (
        <TableAttachment
          fileTypeCode={iup.getPageInstance()?.getGlobalState?.()?.attachmentProperty?.sys_toolbar_column?.fileTypeCode}
          {...restProps}
          style={{ height: '100%', ...style }}
          categoryStyle={{
            borderBottomLeftRadius: 10,
            ...categoryStyle
          }}
          ref={apiRef}
        />
      ),
      async onOk(ins) {
        await handleOk(ins);
      },
      async onCancel(ins) {
        await handleCancel(ins);
      }
    });
  });

export const openFormTableAttachment = (
  apis: any,
  props?: Pick<ITableAttachmentProps, 'control' | 'labelConfig'> & { modal: any }
) => {
  return new Promise((resolve) => {
    const { control = true, labelConfig, modal } = props || {};
    const getResult = async (closeStatus) => {
      const api = apis ?? {};
      const result = await api.getResult();
      return {
        ...result,
        closeStatus
      };
    };
    const handleOk = async (ins) => {
      const api = apis ?? {};
      if (api.uploadingRef.current) {
        iup.message('正在上传中，无法关闭弹窗');
        return;
      }
      if (api.handleValid?.()) {
        await (!control && api?.handleSave?.());
        const result = await getResult('ok');
        ins.destroy();
        resolve(result);
      }
    };
    const handleCancel = async (ins) => {
      const result = await getResult('cancel');
      ins.destroy();
      resolve(result);
    };
    showModal({
      ...defaultAttachmentModalConfig,
      useModal: modal,
      params: { isModal: true, handleOk, handleCancel },
      content: (
        <OriginTableAttachment
          labelConfig={labelConfig}
          style={{ height: '100%' }}
          categoryStyle={{
            borderBottomLeftRadius: 10
          }}
        />
      ),
      async onOk(ins) {
        await handleOk(ins);
      },
      async onCancel(ins) {
        await handleCancel(ins);
      }
    });
  });
};
iup.registerExternal({ openAttachment });
